package top.scsoul.voes.web.controller.examination;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.scsoul.voes.common.constance.ExaminationState;
import top.scsoul.voes.common.constance.OnlineState;
import top.scsoul.voes.common.core.domain.AjaxResult;
import top.scsoul.voes.common.core.domain.entity.User;
import top.scsoul.voes.common.core.domain.model.AnswerSheet;
import top.scsoul.voes.common.core.domain.model.ExameerOnlineVo;
import top.scsoul.voes.common.core.domain.model.IdsVo;
import top.scsoul.voes.examination.entity.ExamRegistration;
import top.scsoul.voes.examination.entity.Examination;
import top.scsoul.voes.examination.entity.QuestionBank;
import top.scsoul.voes.examination.entity.Score;
import top.scsoul.voes.examination.service.ExamRegistrationService;
import top.scsoul.voes.examination.service.ExaminationService;
import top.scsoul.voes.examination.service.ScoreService;
import top.scsoul.voes.framework.web.service.TokenService;
import top.scsoul.voes.system.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/examination")
public class ExaminationController {

    @Autowired
    ExaminationService examinationService;
    @Autowired
    TokenService tokenService;
    @Autowired
    UserService userService;

    @Autowired
    ScoreService scoreService;

    @Value("${token.header}")
    private String header;

    @Autowired
    private ExamRegistrationService examRegistrationService;


    @RequestMapping("/examinations")
    public AjaxResult examinations(
            Examination examination,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo<Examination> examinationPageInfo = examinationService.queryAll(examination, currentPage, pageSize);
        return AjaxResult.success(examinationPageInfo);
    }

    @RequestMapping("/add")
    public AjaxResult add(@Valid Examination examination, HttpServletRequest request) {
        String token = request.getHeader(header);
        String username = tokenService.getUsername(token);
        User user = userService.queryByUsername(username);
        examination.setExamProvider(user.getId());
        return AjaxResult.success(examinationService.insert(examination));
    }

    @RequestMapping("/delete")
    public AjaxResult delete(int id) {
        examinationService.deleteById(id);
        return AjaxResult.success();
    }

    @RequestMapping("/deletes")
    public AjaxResult deletes(@Valid IdsVo idsVo) {
        List<Integer> ids = idsVo.getIds();
        examinationService.deleteByIds(ids);
        return AjaxResult.success();
    }


    @RequestMapping("/update")
    public AjaxResult update(@Valid Examination examination) {
        examinationService.update(examination);
        return AjaxResult.success();
    }

    @RequestMapping("/get/{id}")
    public AjaxResult getById(@PathVariable("id") int Id) {
        Examination examination = examinationService.queryById(Id);
        return AjaxResult.success(examination);
    }

    @RequestMapping("/export")
    public void export(@Valid IdsVo ids, HttpServletResponse response) throws IOException {
        examinationService.export(ids.getIds(), response);
    }

    /**
     * 随机抽题
     */
    @RequestMapping("/randomQuestions")
    public AjaxResult randomQuestions(
            Integer id,
            String keyWord,
            @RequestParam(defaultValue = "0") Long singleChose,
            @RequestParam(defaultValue = "0") Long multipleChose,
            @RequestParam(defaultValue = "0") Long fillBlanks,
            @RequestParam(defaultValue = "0") Long judge,
            @RequestParam(defaultValue = "0") Long subjective) {
        examinationService.randomQuestions(id, keyWord, singleChose, multipleChose, fillBlanks, judge, subjective);
        return AjaxResult.success();
    }

    /**
     * 查看电子试卷(带答案的)
     *
     * @param examId
     * @return
     */
    @RequestMapping("/testPage")
    public AjaxResult testPage(Integer examId) {
        List<QuestionBank> questionBanks = examinationService.testPaper(examId);
        return AjaxResult.success(questionBanks);
    }


    /**
     * 开放
     * 公众查看考试信息 只会返回等待考试的
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/examInfo")
    public AjaxResult examination(
            Examination examination,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {

        examination.setExamState(ExaminationState.BEFORE_THE_EXAM);
        PageInfo<Examination> examinationPageInfo = examinationService.queryAll(examination, currentPage, pageSize);
        return AjaxResult.success(examinationPageInfo);
    }


    /**
     * 报名考试
     *
     * @return
     */
    @RequestMapping("/examRegistration")
    public AjaxResult examRegistration(ExamRegistration examRegistration) {
        return AjaxResult.success(examRegistrationService.insert(examRegistration));
    }

    /**
     * 我的考试
     *
     * @param request
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/myExam")
    public AjaxResult myExam(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        String username = tokenService.getUsername(request);
        PageInfo<Examination> examinationPageInfo = examinationService.queryByUsername(username, currentPage, pageSize);
        return AjaxResult.success(examinationPageInfo);
    }

    /**
     * 根据token的username、前端的examId获取报名信息
     */
    @RequestMapping("/querySelfExamRegistration")
    public AjaxResult querySelfExamRegistration(
            HttpServletRequest request,
            Integer examId) {
        String username = tokenService.getUsername(request);
        ExamRegistration examRegistration = examRegistrationService.queryExamRegistrationByUsernameAndExamId(username, examId);
        return AjaxResult.success(examRegistration);
    }


    /**
     * 用户答题获取试卷 开始考试
     *
     * @param examId
     * @return
     */
    @RequestMapping("/answerSheetTestPaper")
    public AjaxResult answerSheetTestPaper(
            HttpServletRequest request,
            Integer examId) {
        String username = tokenService.getUsername(request);
        List<QuestionBank> questionBanks = examinationService.answerSheetTestPaper(username, examId);
        return AjaxResult.success(questionBanks);
    }


    /**
     * 交卷
     *
     * @param request
     * @param examId
     * @param answerSheet
     * @return
     */
    @RequestMapping("/submitAnswerSheet")
    public AjaxResult submitAnswerSheet(
            HttpServletRequest request,
            @RequestParam("examId") Integer examId,
            @RequestBody List<AnswerSheet> answerSheet) {
        String username = tokenService.getUsername(request);
        examinationService.submitAnswerSheet(examId, username, answerSheet);
        return AjaxResult.success();
    }


    /**
     * 获取参加考生信息
     * 监控使用
     *
     * @param examId
     * @return
     */
    @RequestMapping("/getOnlineExameeInfo")
    public AjaxResult getOnlineExameeInfo(
            @RequestParam("examId") Integer examId) {
        List<ExamRegistration> onlineExameeInfo = examinationService.getOnlineExameeInfo(examId);

        return AjaxResult.success(onlineExameeInfo);
    }


    /**
     * .考试心跳
     *
     * @param exameerOnlineVo
     * @return
     */
    @RequestMapping("/exameeOnliner")
    public void exameeOnliner(
            ExameerOnlineVo exameerOnlineVo) {
        examinationService.exameeOnliner(exameerOnlineVo);
    }

    /**
     * 获取心跳  监控台
     *
     * @param examId
     * @return
     */
    @RequestMapping("/getOnlineExameeHeat")
    public AjaxResult getOnlineExameeHeat(Integer examId) {
        Map<String, Object> map = examinationService.getOnlineExameeHeat(examId);
        return AjaxResult.success(map);
    }


    /**
     * 阅卷
     *
     * @param examId
     */
    @RequestMapping("/markingExamPapers")
    public AjaxResult markingExamPapers(
            Integer examId) {
        Integer state = examinationService.checkState(examId);
        if (!ExaminationState.END_OF_EXAM.equals(state)) {
            return AjaxResult.error("该考试未达到阅卷要求");
        }
        //拿出所有与该考试相关试卷的自选题
        return AjaxResult.success();
    }

    /**
     * 公布成绩
     *
     * @param examId
     * @return
     */
    @RequestMapping("/announceResults")
    public AjaxResult announceResults(
            Integer examId) {
        Integer state = examinationService.checkState(examId);
        if (!ExaminationState.END_OF_EXAM.equals(state)) {
            return AjaxResult.error("该考试未达到公布成绩要求");
        }
        Examination examination = new Examination();
        examination.setId(examId);
        examination.setExamState(ExaminationState.QUERY_SCORE_EXAM);
        examinationService.update(examination);
        return AjaxResult.success();
    }


    /**
     * 查询自己的分数
     *
     * @param request
     * @param examId
     * @return
     */
    @RequestMapping("/selfScoreQuery")
    public AjaxResult selfScoreQuery(
            HttpServletRequest request,
            Integer examId) {
        Integer state = examinationService.checkState(examId);
        if (!ExaminationState.QUERY_SCORE_EXAM.equals(state)) {
            return AjaxResult.error("还没有到达查询成绩时间");
        }
        String username = tokenService.getUsername(request);
        //
        Float score = scoreService.querySelfScore(username, examId);
        return AjaxResult.success(score);
    }

    /**
     * 考试完成后查看自己的错题
     *
     * @param request
     * @param examId
     * @return
     */
    @RequestMapping("/selfTestPaperQuery")
    public AjaxResult selfTestPaperQuery(
            HttpServletRequest request,
            Integer examId) {
        Integer state = examinationService.checkState(examId);
        if (!ExaminationState.QUERY_SCORE_EXAM.equals(state)) {
            return AjaxResult.error("还没有到达查询时间");
        }
        String username = tokenService.getUsername(request);
        Map<String, Object> dataMap = scoreService.queryByUsernameAndExamId(username, examId);
        Float score = scoreService.querySelfScore(username, examId);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("data", dataMap);
        map.put("score", score);
        return AjaxResult.success(map);
    }
}



